package kr.co.bettersoft.usedmarketandroid.activity;

import java.util.Locale;

import kr.co.bettersoft.usedmarketandroid.common.CommonConstant;
import kr.co.bettersoft.usedmarketandroid.common.CommonUtil;
import kr.co.bettersoft.usedmarketandroid.common.UsedMarketRest;
import kr.co.bettersoft.usedmarketandroid.domain.UsedMarketMember;
import kr.co.bettersoft.usedmarketandroid.domain.UsedMarketSMS;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
/**
 * 멤버 등록 후 멤버 등록 메뉴를 터치했을때
 *  인증, 등록된 휴대전화번호를 출력
 *  멤버 등록 여부는 휴대전화 번호가 설정 파일에 저장되어있는지 여부로 판단
 *  
 * 상단 뒤로 버튼 누르면 설정으로 돌아감
 * @author blue
 *
 */
public class UsedMarketRetireActivity extends Activity{
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// 변수

	String TAG = "UsedMarketCertiInfoActivity.java";

	public final int DEACTIVATE_USER = 101; // 멤버 탈퇴하기

	String phoneNum = "";

	// 설정 파일 저장소  
	SharedPreferences sharedPrefCustom;

	// 화면 구성
	Button backBtn;										// 뒤로가기 버튼
	Button retireBtn;									// 탈퇴 버튼
	
	
	ProgressBar pb1;								// 중단 로딩 진행바
	/////////////////////////////////////////////////////////////////////////////////////////////////////////////	
	// 핸들러
	Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			Bundle b = msg.getData();
			try{
				if(b.getInt("showErrToast")==1){
					Toast.makeText(UsedMarketRetireActivity.this,b.getString("msg"), Toast.LENGTH_SHORT).show();
				}
				if(b.getInt("showAlert")==1){					 // 알림 및 경고창 . 
					new AlertDialog.Builder(returnThis())
					.setTitle(CommonConstant.alertTitle)							
					.setMessage(b.getString("msg"))
					.setIcon(R.drawable.ic_launcher)		// 경고창.  
					.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							// 그냥 사용자 확인 용이기 때문에 추가 조작 없음.
						}})
						.setNegativeButton("", null).show();
				}		 
				if(b.getInt("confirmRetire")==1){		
					new AlertDialog.Builder(returnThis())
					.setTitle(CommonConstant.alertTitle)							
					.setMessage("탈퇴하시겠습니까?")
					.setIcon(R.drawable.ic_launcher)		// 경고창.  
					.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							// 탈퇴 진행
							Log.d(TAG,"retire..");
							handler.sendEmptyMessage(DEACTIVATE_USER);
						}})
						.setNegativeButton(android.R.string.no, null)		 
						.show();	// 탈퇴 취소
				}
				if(b.getInt("order")==1){
					// 프로그래스바 실행
					pb1.setVisibility(View.VISIBLE);
				}else if(b.getInt("order")==2){
					// 프로그래스바  종료
					pb1.setVisibility(View.INVISIBLE);
				}

				switch (msg.what)
				{
				case DEACTIVATE_USER : runOnUiThread(new RunnableUpdateDeactivate());				
				break;
				default : 
					break;
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	};


	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	


	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature( Window.FEATURE_NO_TITLE );
		setContentView(R.layout.usedmarket_retire_activity);

		// prefs
		sharedPrefCustom = getSharedPreferences(CommonConstant.prefName,
				Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);


		// 전번 세팅
		phoneNum = sharedPrefCustom.getString("phoneNum", "");

		
		pb1=(ProgressBar) findViewById(R.id.progressbar);	


		// 뒤로가기 버튼
		backBtn = (Button) findViewById(R.id.backBtn);	// 뒤로 버튼
		backBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		// 탈퇴 버튼
		retireBtn = (Button) findViewById(R.id.retireBtn);	// 뒤로 버튼
		retireBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				confirmRetire();
			}
		});
	}

	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// 서버통신
	
	/**
	 * 러너블. 멤버 탈퇴  updateDeactivate
	 */
	class RunnableUpdateDeactivate implements Runnable {
		public void run(){
			new backgroundThreadUpdateDeactivate().execute();
		}
	}
	/**
	 * backgroundThreadUpdateDeactivate
	 * 비동기    서버와 통신하여 서버와 통신하여 멤버 탈퇴 
	 * @author blue
	 *
	 */
	public class backgroundThreadUpdateDeactivate extends AsyncTask<Void, Void, Void>{
		@Override protected void onPostExecute(Void result) {  
		} 
		@Override protected void onPreExecute() {  
		} 
		@Override protected Void doInBackground(Void... params) {  
			Log.d(TAG,"backgroundThreadUpdateDeactivate");

			// 파라미터 세팅

			UsedMarketMember usedMarketMember = new UsedMarketMember();
			usedMarketMember.setPhoneNumber(phoneNum);

			// 서버 메소드 호출
			showPb();
			UsedMarketRest usedMarketRest = new UsedMarketRest();
			String result = usedMarketRest.RestUpdateDeactivate(usedMarketMember);
			Log.d(TAG,"backgroundThreadUpdateDeactivate result::"+result);
			if(result.equals("SUCCESS")){
				// 탈퇴 성공.

				// 멤버 정보 삭제 
				SharedPreferences sharedPreferences = getSharedPreferences(CommonConstant.prefName, Activity.MODE_PRIVATE);
				SharedPreferences.Editor editor = sharedPreferences.edit();
				phoneNum = "";
				editor.putString("agreedYN", "N");			// 인증 여부 저장
				editor.putString("phoneNum", "");		// 전번도 저장	 
				editor.commit();

				alert("탈퇴 되었습니다.");	
			}else{
				// 인증 실패.
				alert("요청이 실패하였습니다.");
			}
			hidePb();
			return null; 
		}
	}

	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	public Context returnThis(){
		return this;
	}


	// 중앙 프로그래스바 보임, 숨김
	/**
	 * showPb
	 *  중앙 프로그래스바 가시화한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void showPb(){
		UsedMarketRetireActivity.this.runOnUiThread(new Runnable(){		 
			@Override
			public void run(){
				Message message = handler .obtainMessage();
				Bundle b = new Bundle();
				b.putInt( "order" , 1);
				message.setData(b);
				handler .sendMessage(message);
			}
		});
	}
	/**
	 * hidePb
	 *  중앙 프로그래스바 비가시화한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void hidePb(){
		UsedMarketRetireActivity.this.runOnUiThread(new Runnable(){		 
			@Override
			public void run(){
				Message message = handler .obtainMessage();
				Bundle b = new Bundle();
				b.putInt( "order" , 2);
				message.setData(b);
				handler .sendMessage(message);
			}
		});
	}

	/**
	 * alert
	 * 얼럿 창 띄우기
	 *
	 * @param msg
	 * @param 
	 * @return 
	 */
	public void alert(final String msg){
		runOnUiThread(new Runnable(){
			public void run(){
				Message message = handler.obtainMessage();				
				Bundle b = new Bundle();
				b.putInt("showAlert", 1);
				b.putString("msg", msg);			// 화면에 보여줄 메시지
				message.setData(b);
				handler.sendMessage(message);
			}
		});
	}
	/**
	 * confirmRetire
	 * 얼럿 창 띄우기 - 탈퇴 확인
	 *
	 * @param msg
	 * @param 
	 * @return 
	 */
	public void confirmRetire(){
		runOnUiThread(new Runnable(){
			public void run(){
				Message message = handler.obtainMessage();				
				Bundle b = new Bundle();
				b.putInt("confirmRetire", 1);
				message.setData(b);
				handler.sendMessage(message);	
			}
		});
	}
}
